package VideoTools;

import java.awt.Component;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.control.FrameRateControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;

public class VideoPlayer {

	public static final int size_X=320;
	public static final int size_Y=240;
	private String driver;
	private String url;
	private MediaLocator ml;
	private static Player player = null;
	public static final int frameRatePerDefault = 30;
	private static final int frameRateUnacceptableUnder = 1;
	private static boolean isLaunch=false;
	
	
	public VideoPlayer(String driver, String url) throws VideoPlayerException {
		super();
		this.driver = driver;
		this.url = url;
		this.init();
		
	}
	
	public static boolean getIsLaunch(){
		return isLaunch;
	}
	
	private void init() throws VideoPlayerException {
		
		
	
		try {
			String driver = "vfw:Microsoft WDM Image Capture (Win32):0";
			CaptureDeviceInfo di = CaptureDeviceManager.getDevice(driver);
			ml = new MediaLocator("vfw://0");
			player = Manager.createRealizedPlayer(ml);
			
		} catch (NoPlayerException e) {
			throw new VideoPlayerException(e.getMessage());
		} catch (CannotRealizeException e) {
			throw new VideoPlayerException(e.getMessage());
		} catch (IOException e) {
			throw new VideoPlayerException(e.getMessage());
		}
	}
	
	public void start() throws VideoPlayerException{
		player.start();
	}
	
	public Component getVisualComponent(){
		return player.getVisualComponent();
	}
	
	public void stop(){
		player.stop();
	}
	
	public void exit(){
		player.deallocate();
	}
	
	/**
	 * @return an image or null if there is no image
	 */
	public Image getOneFrame(){
		//		 Grab a frame
		FrameGrabbingControl fgc = (FrameGrabbingControl)
		player.getControl("javax.media.control.FrameGrabbingControl");
		Buffer buf= fgc.grabFrame();
		if (buf!=null){
		//		Convert it to an image
		BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
		return btoi.createImage(buf);
		}
		else return null;
	}

	
	public double getFrameRate(){
		FrameRateControl gfr = (FrameRateControl)player.getControl("javax.media.control.FrameRateControl");
		if (gfr.getFrameRate()<frameRateUnacceptableUnder){
			return frameRatePerDefault;
		}
		isLaunch=true;
		return gfr.getFrameRate();
		
	}
	
	
	public String getDriver() {
		return driver;
	}
	
	public String getUrl() {
		return url;
	}
	
	
	
}
